//
//  TicketOrderVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/12/15.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "TicketOrderVC.h"
#import "TicketPurchaseInfor.h"
#import "AppointmentTimeCell.h"
#import "AddTicketMemberCell.h"
#import "SelectedTimeView.h"
#import "OrderConfirmVC.h"
#import "AddTicketMemberVC.h"
#import "TicketModel.h"
#import "TicketOrderModel.h"
#import "TicketPurchaseTipVC.h"
@interface TicketOrderVC ()<UITableViewDelegate,UITableViewDataSource,AddTicketMenberDelegate,AppointmentTimeCellDelegate,AddTicketMemberVCDelegate,SelectedTimeViewDelegate,TicketPurchaseInforDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;


@property (weak, nonatomic) IBOutlet UIView *BtnView;

@property (weak, nonatomic) IBOutlet UILabel *prcieLabel;

@property (nonatomic, strong)SelectedTimeView * selectedTimeView;
@property (nonatomic, strong)UIView * containerView;

@property (nonatomic, strong)TicketOrderModel * orderModel;

@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@property (nonatomic, assign)BOOL isNeedTime;
@end

@implementation TicketOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self popSelectTimeView];
    });
    // Do any additional setup after loading the view from its nib.
    [self loadData];
}

- (void)loadData {
    
    self.orderModel = [[TicketOrderModel alloc] init];
    self.orderModel.ticketDetailModel = self.ticketDetailModel;
    self.prcieLabel.text = self.orderModel.oderSunMoney;
}

- (void)popSelectTimeView {
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.selectedTimeView.frame = CGRectMake(0, kNavigationBarHeight, kScreenWidth, (kScreenWidth - 40)/7 * 6 + (self.isNeedTime ? 200:100));
        self.containerView.alpha = 1;
    }];
    self.selectedTimeView.currentDate = self.orderModel.date;
}

- (void)closeSelectTimeView {
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.selectedTimeView.frame = CGRectMake(0, -((kScreenWidth - 40)/7 * 6 + 136), kScreenWidth, (kScreenWidth - 40)/7 * 6 +(self.isNeedTime ? 200:100));
         self.containerView.alpha = 0;
    }];
    
    [self.tableView reloadData];
}

- (SelectedTimeView *)selectedTimeView {
    
    if (!_selectedTimeView) {
        
        if ([self.ticketDetailModel.usetime isEqualToString:@"time"]) {
            self.isNeedTime = YES;
        }
        
        _selectedTimeView = [[SelectedTimeView alloc] initWithFrame:CGRectMake(0, -((kScreenWidth - 40)/7 * 6 + 136), kScreenWidth, (kScreenWidth - 40)/7 * 6 + (self.isNeedTime ? 200:100))];
        _selectedTimeView.delegate = self;
        
        _selectedTimeView.daysLimit = self.orderModel.ticketDetailModel.dayslimit;
        
        _selectedTimeView.closeArray = [NSMutableArray arrayWithArray:self.orderModel.ticketDetailModel.close];
        
        _selectedTimeView.isNeedTime = self.isNeedTime;
        [self.view addSubview:_selectedTimeView];
    }
    
    return _selectedTimeView;
}

- (UIView *)containerView {
    
    if (!_containerView) {
        
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0,kNavigationBarHeight, kScreenWidth, kScreenHeight)];
        _containerView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        
        _containerView.alpha = 0;
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeSelectTimeView)];
        
        [_containerView addGestureRecognizer:tap];
    }
    
    return _containerView;
}
- (IBAction)nextBtnClicketed:(id)sender {
    
    if (self.orderModel.dateStr.length == 0 || [self.orderModel sumMoney] == 0) {
        
        NSString * str = MYLocalizedString(@"TICKET_SELECT_RESERVATION_INFO", nil);
        if(self.orderModel.dateStr.length == 0 && [self.orderModel sumMoney] == 0){
            str = MYLocalizedString(@"TICKET_SELECT_RESERVATION_INFO", nil);
        }else if (self.orderModel.dateStr.length == 0) {
            str = MYLocalizedString(@"TICKET_SELECT_RESERVATION_DATE", nil);
        }else if([self.orderModel sumMoney] == 0){
            str = MYLocalizedString(@"TICKET_SELECT_RESERVATION_NUM",nil);
        }
        
        [IGAlertView alertWithTitle:MYLocalizedString(@"TICKET_SELECT_RESERVATION_TIP", nil) message:str cancelButtonTitle:MYLocalizedString(@"TICKET_SELECT_RESERVATION_GOON", nil) commitBtn:nil commit:nil cancel:nil];
        return;
    }
    
    OrderConfirmVC * vc = [[OrderConfirmVC alloc] init];
    
    
    vc.ticketOrderModel.visitors = [NSMutableArray arrayWithArray:self.orderModel.orderRequestInfoArray];
    vc.ticketOrderModel.amount = self.orderModel.oderSunMoney;
    vc.ticketOrderModel.realpay = self.orderModel.oderSunMoney;
    vc.ticketOrderModel.orderdate = self.orderModel.dateStr;
    vc.ticketOrderModel.ticketID = self.orderModel.ticketDetailModel.tid;
    vc.ticketOrderModel.subject = self.orderModel.ticketDetailModel.title;
    vc.ticketOrderModel.visitdate = self.orderModel.dateStr;
    vc.ticketOrderModel.APM = self.orderModel.APM;
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)setup{

    self.topSpace.constant = kNavigationBarHeight;
    [self.tableView registerNib:[UINib nibWithNibName:@"TicketPurchaseInfor" bundle:nil] forCellReuseIdentifier:@"TicketPurchaseInfor"];
    [self.tableView registerNib:[UINib nibWithNibName:@"AppointmentTimeCell" bundle:nil] forCellReuseIdentifier:@"AppointmentTimeCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"AddTicketMemberCell" bundle:nil] forCellReuseIdentifier:@"AddTicketMemberCell"];

    [self.view addSubview:self.containerView];
    
    [self.nextBtn setTitle:MYLocalizedString(@"TICKET_BOOK_NEXT", nil) forState:UIControlStateNormal];
    self.title = MYLocalizedString(@"TICKET_BOOK_VCTITLE",nil);
    [self setNavThemeGradient];

}
#pragma mark --TicketPurchaseInforDelegate

- (void)goPurhchaseTipWith:(NSString *)detail {
    
    TicketPurchaseTipVC * tipVC = [[TicketPurchaseTipVC alloc] init];
    
    tipVC.detail = detail;
    
    [self.navigationController  pushViewController:tipVC animated:YES];
}

#pragma mark -- AppointmentTimeCellDelegate

- (void)goSelectCalendar {
    
    [self popSelectTimeView];
}

#pragma mark --SelectedTimeViewDelegate

- (void)selectTheDate:(NSDate *)date Time:(NSString *)time isNeedTime:(BOOL)flag {
    
    if (flag) {
        
        if (date && time.length > 0) {
            
            self.orderModel.dateStr = self.selectedTimeView.currentDateStr;
            self.orderModel.date = self.selectedTimeView.currentDate;
            self.orderModel.APM = time;
            [self closeSelectTimeView];
            
        }
    }else{
        
        if (date) {
            self.orderModel.dateStr = self.selectedTimeView.currentDateStr;
            self.orderModel.date = self.selectedTimeView.currentDate;
            [self closeSelectTimeView];
        }
    }
}

#pragma mark -- AddTicketMenberDelegate

- (void)addMemBerType:(NSInteger)type {
    
    AddTicketMemberVC * vc = [[AddTicketMemberVC alloc] init];
    
    vc.delegate =self;
    vc.type = type;
    switch (type) {
        case AdultTicket:
        {
            [vc.selectedMembers addObjectsFromArray:self.orderModel.adultArray];
        }
            break;
        case ChildrenTicket:
        {
            [vc.selectedMembers addObjectsFromArray:self.orderModel.childArray];
        }
            break;
        case ElderTicket:
        {
           [vc.selectedMembers addObjectsFromArray:self.orderModel.elderArray];
        }
            break;
        case MemberTicket:
        {
            [vc.selectedMembers addObjectsFromArray:self.orderModel.memberArray];
        }
            break;
        default:
            break;
    }
    
    vc.mustLimiteArray = [NSArray arrayWithArray:self.orderModel.ticketDetailModel.needinfo];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)addMemBerType:(NSInteger)type WithNum:(NSInteger)num {
    
    switch (type) {
        case AdultTicket:
        {
            self.orderModel.adultTickets = num;
        }
            break;
        case ChildrenTicket:
        {
            self.orderModel.childTickets = num;
        }
            break;
        case ElderTicket:
        {
            self.orderModel.elderTickedts = num;
        }
            break;
        case MemberTicket:
        {
            self.orderModel.elderTickedts = num;
        }
            break;
        default:
            break;
    }
    
    self.prcieLabel.text = self.orderModel.oderSunMoney;
    
    IGLog(@"准备购买  %ld 张",num);
}
- (void)deleteMemberWith:(TicketMemberInfoModel *)model WithType:(NSInteger)type {
   
    switch (type) {
        case AdultTicket:
        {
            if ([self.orderModel.adultArray containsObject:model]) {
             
                [self.orderModel.adultArray removeObject:model];
            }
        }
            break;
        case ChildrenTicket:
        {
            if ([self.orderModel.childArray containsObject:model]) {
                
                [self.orderModel.childArray removeObject:model];
            }
        }
            break;
        case ElderTicket:
        {
            if ([self.orderModel.elderArray containsObject:model]) {
                
                [self.orderModel.elderArray removeObject:model];
            }
        }
            break;
        case MemberTicket:
        {
            if ([self.orderModel.memberArray containsObject:model]) {
                
                [self.orderModel.memberArray removeObject:model];
            }
        }
            break;
        default:
            break;
    }
        self.prcieLabel.text = self.orderModel.oderSunMoney;
            [self.tableView reloadData];
}


#pragma mark -- AddTicketMemberVCDelegate

- (void)completeAddWithMembers:(NSArray *)memberArray Type:(TicketType)type {
    
    switch (type) {
        case AdultTicket:
        {
            self.orderModel.adultArray =[NSMutableArray arrayWithArray:memberArray] ;
            
        }
            break;
        case ChildrenTicket:
        {
            self.orderModel.childArray =[NSMutableArray arrayWithArray:memberArray] ;
        }
            break;
        case ElderTicket:
        {
            self.orderModel.elderArray =[NSMutableArray arrayWithArray:memberArray] ;
        }
            break;
        case MemberTicket:
        {
            self.orderModel.memberArray =[NSMutableArray arrayWithArray:memberArray] ;
        }
            break;
        default:
            break;
    }
    self.prcieLabel.text = self.orderModel.oderSunMoney;
    [self.tableView reloadData];
}

#pragma  mark   -- UITableViewDelegate,UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section < 2) {
        return 1;
    }
    
    return self.orderModel.ticketDetailModel.ticketTypes.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        TicketPurchaseInfor * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketPurchaseInfor"];
        cell.delegate = self;
        [cell configData:self.orderModel.ticketDetailModel];
        
        return cell;
    }else if(indexPath.section == 1){
        
        AppointmentTimeCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AppointmentTimeCell"];
        
        cell.timeNameLabel.text = MYLocalizedString(@"TICKET_ORDER_DATE", nil);
        if (self.orderModel.dateStr.length > 0) {
            cell.appointTimeLabel.text = self.orderModel.dateStr;
        }else {
            cell.appointTimeLabel.text = MYLocalizedString(@"TICKET_CHOOSE_DATE", nil);
        }
        
        cell.delegate = self;
        return cell;
    }else{
        
        TicketTypeModel * model = self.orderModel.ticketDetailModel.ticketTypes[indexPath.row];
        
        AddTicketMemberCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AddTicketMemberCell"];
//        if (indexPath.row == 0) {
//            model.needdetail = YES;
//        }
        cell.delegate = self;
        
        [cell configTicketType:model];
        
        if (model.needdetail) {
            
            switch (model.type.integerValue) {
                case 1:
                {
                    cell.dataSource = self.orderModel.adultArray;
                }
                    break;
                case 2:
                {
                    cell.dataSource = self.orderModel.childArray;
                }
                    break;
                case 3:
                {
                    cell.dataSource = self.orderModel.elderArray;
                }
                    break;
                case 4:
                {
                    cell.dataSource = self.orderModel.memberArray;
                }
                    break;
                default:
                    break;
            }
        }
       
        return cell;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return 90;
    }else if(indexPath.section == 1){
        
        return 60;
    }else {
        
        TicketTypeModel * model = self.orderModel.ticketDetailModel.ticketTypes[indexPath.row];
        
        if (model.needdetail) {
            
            switch (model.type.integerValue) {
                case 1:
                    
                    return [AddTicketMemberCell getCellHeightWith:self.orderModel.adultArray.count];
                    break;
                case 2:
                    
                    return [AddTicketMemberCell getCellHeightWith:self.orderModel.childArray.count];
                    break;
                case 3:
                    
                    return [AddTicketMemberCell getCellHeightWith:self.orderModel.elderArray.count];
                case 4:
                    return [AddTicketMemberCell getCellHeightWith:self.orderModel.memberArray.count];
                    break;
                 default:
                    return 50;
                    break;
            }
            
        }else{
            
            return 50;
        }
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
